﻿#include "ExampleLayer.h"
#include"Events/KeyEvents.h"


ExampleLayer::ExampleLayer()
	: Layer("ExampleLayer"), m_Camera(-1.6f, 1.6f, -.9f, 0.9f)
{
	m_VertexArray.reset(ArsEngine::VertexArray::Create());

	float vertices[] = {
		-0.5f, -0.5f, 0.0f,1.0f, 0.0f, 0.0f, 1.0f,
		0.5f, -0.5f, 0.0f,1.0f, 1.0f, 0.0f, 1.0f,
		0.0f, 0.5f, 0.0f,1.0f, 0.0f, 1.0f, 1.0f
	};

	unsigned int indices[] = {
		0, 1, 2
	};

	m_VertexBuffer.reset(ArsEngine::VertexBuffer::Create(vertices, sizeof(vertices)));
	m_IndexBuffer.reset(ArsEngine::IndexBuffer::Create(indices, 3));

	ArsEngine::BufferLayout layout =
	{
	  {ArsEngine::ShaderDataType::Float3, "aPos"},
	  {ArsEngine::ShaderDataType::Float4, "aColor"}
	  // {ShaderDataType::Float3, "aNormal"},
	};

	m_VertexBuffer->SetLayout(layout);

	m_VertexArray->AddVertexBuffer(m_VertexBuffer);
	m_VertexArray->SetIndexBuffer(m_IndexBuffer);

	std::string vertexShader = R"(
            #version 330 core
            layout (location = 0) in vec3 aPos;
            layout (location = 1) in vec4 aColor;

            uniform mat4 u_ViewProjection;

            out vec4 FragColor;
            void main()
            {
                gl_Position = u_ViewProjection * vec4(aPos.x, aPos.y, aPos.z, 1.0);
                FragColor = aColor;
            }
        )";

	std::string fragmentShader = R"(
            #version 330 core
            out vec4 Color;
            in vec4 FragColor;

            void main()
            {
              Color = FragColor;
            }
        )";

	m_Shader.reset(new ArsEngine::Shader(vertexShader.c_str(), fragmentShader.c_str()));
}

void ExampleLayer::OnUpdate(ArsEngine::TimeStep ts)
{
	AN_TRACE("Delta time: {0} seconds({1} ms)", ts.GetSeconds(),ts.GetMilliseconds());

	if (ArsEngine::Input::IsKeyPressed(AN_KEY_LEFT))
	{
		m_CameraPosition.x -= m_CameraSpeed*ts;
	}
	else if (ArsEngine::Input::IsKeyPressed(AN_KEY_RIGHT))
	{
		m_CameraPosition.x += m_CameraSpeed*ts;
	}

	if (ArsEngine::Input::IsKeyPressed(AN_KEY_UP))
	{
		m_CameraPosition.y += m_CameraSpeed*ts;
	}
	else if (ArsEngine::Input::IsKeyPressed(AN_KEY_DOWN))
	{
		m_CameraPosition.y -= m_CameraSpeed*ts;
	}

	ArsEngine::RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1.0f });
	ArsEngine::RenderCommand::Clear();
	m_Camera.SetPosition(m_CameraPosition);
	m_Camera.SetRotation(0.0f);

	ArsEngine::Renderer::BeginScene(m_Camera);

	ArsEngine::Renderer::Submit(m_VertexArray, m_Shader);

	ArsEngine::Renderer::EndScene();

}

void ExampleLayer::OnEvent(ArsEngine::Event& event)
{

}



void ExampleLayer::OnImGuiRender()
{
	//AN_TRACE("ExampleLayer::OnImGuiRender() called");
	ImGui::Begin("ExampleLayer");
	ImGui::Text("Hello World from ImGui!");
	ImGui::End();
}
